package com.envper.common.service.alarm.impl;

import com.envper.common.domain.alarm.AlarmType;
import com.envper.common.domain.dto.AlarmDto;
import com.envper.common.exception.GlobalException;
import com.envper.common.mapper.AlarmMapper;
import com.envper.common.service.alarm.AlarmService;
import com.envper.common.util.IdUtils;
import com.envper.mysql.base.service.AlarmBaseService;
import com.envper.mysql.domain.Status;
import com.envper.mysql.domain.entity.TAlarm;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class AlarmServiceImpl implements AlarmService {
    private final AlarmBaseService alarmBaseService;

    @Override
    public List<AlarmDto> getAlarmList() {
        List<TAlarm> list = alarmBaseService.list();
        return AlarmMapper.INSTANCE.toAlarmDtoList(list);
    }

    @Override
    @Transactional
    public void triggerAlarm(Long deviceId, AlarmType alarmType) {
        TAlarm alarm = TAlarm.builder()
                .id(IdUtils.createId())
                .deviceId(deviceId)
                .content(alarmType.getContent())
                .created(LocalDateTime.now())
                .build();
        boolean save = alarmBaseService.save(alarm);
        if (!save) throw new GlobalException(Status.SAVEERROR);
    }
}
